import 'package:stacked/stacked.dart';
import 'package:vista/shared/models/daily_inspiration.dart';
import 'package:vista/shared/models/moment_shot.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/daily_inspiration_service.dart';
import 'package:vista/shared/services/post_studio.dart';

/// 首页视图模型
/// 管理首页的数据和状态
class HomeViewModel extends BaseViewModel {
  final AuthFocus _authFocus;
  final DailyInspirationService _dailyInspirationService;
  final PostStudio _postStudio;

  HomeViewModel(
    this._authFocus,
    this._dailyInspirationService,
    this._postStudio,
  );

  List<DailyInspiration> _dailyInspirations = [];
  List<DailyInspiration> get dailyInspirations => _dailyInspirations;

  List<MomentShot> _photographyPosts = [];
  List<MomentShot> get photographyPosts => _photographyPosts;

  Map<String, UserFrame> _userMap = {};
  UserFrame? getUserById(String userId) => _userMap[userId];

  /// 初始化数据
  Future<void> initialize() async {
    setBusy(true);
    try {
      await _loadDailyInspirations();
      await _loadPhotographyPosts();
      await _loadUsers();
    } finally {
      setBusy(false);
    }
  }

  /// 加载每日灵感
  Future<void> _loadDailyInspirations() async {
    _dailyInspirations = await _dailyInspirationService.getAllInspirations();
    // 只取前3个
    _dailyInspirations = _dailyInspirations.take(3).toList();
    notifyListeners();
  }

  /// 加载摄影类型动态
  Future<void> _loadPhotographyPosts() async {
    _photographyPosts = await _postStudio.getPostsByCategory(
      PostCategory.photography,
    );
    notifyListeners();
  }

  /// 加载用户信息
  Future<void> _loadUsers() async {
    final users = await _authFocus.getUsers();
    _userMap = {for (var user in users) user.id: user};
    notifyListeners();
  }

  /// 刷新数据
  Future<void> refresh() async {
    await initialize();
  }

  /// 删除动态
  Future<void> deletePost(String postId) async {
    await _postStudio.deletePost(postId);
    // 重新加载摄影类型动态
    await _loadPhotographyPosts();
  }
}
